const dragEventHandler = (el, binding, vNode) => {
    let value = binding.value;
    if (value) {
        //目标对象的鼠标按下事件
        el.onmousedown = (e) => {
            e.stopPropagation();
            let index = $(el).attr('index');
            if (index) {
                index = Number(index);
            }
            let dataId = $(el).attr('dataId');
            if (dataId) {
                index = dataId;
            }
            let oldLeft = el.style.left,
                oldTop = el.style.top;
            //鼠标相对元素的位置
            let disX = e.clientX - el.offsetLeft;
            let disY = e.clientY - el.offsetTop;
            let positionLeft = 0,
                positionTop = 0;
            document.onmousemove = (m) => {
                //元素的位置=鼠标位置-鼠标相对元素的位置
                let leftA = m.clientX - disX;
                let topA = m.clientY - disY;
                //设置边界
                positionLeft = leftA < 0 ? 0 : leftA > value.width - 1 - el.offsetWidth ? value.width - 1 - el.offsetWidth : leftA;
                positionTop = topA < 0 ? 0 : topA > value.height - 1 - el.offsetHeight ? value.height - 1 - el.offsetHeight : topA;
                el.style.left = positionLeft + 'px';
                el.style.top = positionTop + 'px';
            };
            //document的鼠标弹起事件：清空鼠标移动和弹起事件
            document.onmouseup = () => {
                document.onmousemove = null;
                document.onmouseup = null;
                if (oldLeft !== el.style.left || oldTop !== el.style.top) {
                    if (vNode.context.updatePosition) {
                        vNode.context.updatePosition(index, positionLeft, positionTop);
                    }
                }
            }
        };
    }
};

/**
 * 部位拖拽指令
 */
export default {
    bind(el, binding, vNode) {
        dragEventHandler(el, binding, vNode);
    },
    update(el, binding, vNode) {
        dragEventHandler(el, binding, vNode);
    },
};
